<template>
    <div class="memberinfo-layout"
    >
        <div class="info-back search-part">
            <el-row :gutter="20">
                <el-col :span="12">
                    <div class="back-icon" @click="back()">
                        <i class="fa fa-arrow-left" aria-hidden="true"></i>
                    </div>
                </el-col>
                <el-col :span="10" class="btns">
                    <el-button type="primary" class="save red-btn" @click="submitForm('ruleForm')">保存</el-button>
                </el-col>
            </el-row>

        </div>
        <div class="info-form">

            <el-form :model="ruleForm" :rules="rulesUser" ref="ruleForm" label-width="100px" class="demo-ruleForm">

                <el-row :gutter="20">

                    <el-form-item label="姓名：" prop="name"
                                  :rules="[
                  {
                      required: true,
                      message: '请输入名称',
                      trigger: 'change'
                  }
                ]">
                        <el-input v-model="ruleForm.name"></el-input>
                    </el-form-item>


                    <el-form-item label="学号：" prop="account"
                                  :rules="[
                  {
                      required: true,
                      message: '请输入账户',
                      trigger: 'change'
                  }
                ]">
                        <el-input v-model="ruleForm.account" :disabled="isDisabled"></el-input>
                    </el-form-item>


                    <el-form-item
                            prop="password"
                            label="密码："

                    >
                        <el-input type="password" v-model="ruleForm.password" placeholder="*** ***"
                                  autocomplete="new-password" auto-complete="new-password"></el-input>
                    </el-form-item>


                    <el-form-item
                            prop="tel"
                            label="电话："
                            :rules="[
                    {
                        pattern: /^[1]\d{10}$/,
                        message: '请输入正确的电话号码',
                        trigger: 'blur'
                    }
                  ]"
                    >
                        <el-input v-model="ruleForm.tel"></el-input>
                    </el-form-item>


                    <el-form-item
                            prop="email"
                            label="邮箱："
                            :rules="[
                   { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' }
                 ]"
                    >
                        <el-input v-model="ruleForm.email"></el-input>
                    </el-form-item>


                    <el-form-item label="状态：" prop="state">
                        <div class="el-left">
                            <el-switch on-text="启用"
                                       off-text=""
                                       v-model="status"
                                       on-color="#13ce66"
                                       off-color="#cacaca"
                            ></el-switch>
                        </div>
                    </el-form-item>

                    <el-form-item label="可视单位：" prop="userOrganNames">
                        <el-input v-model="ruleForm.userOrganNames" v-on:focus="selectOrgans" readonly></el-input>
                    </el-form-item>

                    <el-form-item label="主单位：" prop="primaryOrganName"
                                  :rules="[
                              {
                                  required: true,
                                  message: '请选择主机构',
                                  trigger: 'change'
                              }
                            ]"
                    >
                        <el-input v-model="ruleForm.primaryOrganName" v-on:focus="selectOrgan" readonly></el-input>
                    </el-form-item>

                    <el-form-item label="职位：" prop="userRoleNames">
                        <el-input v-model="ruleForm.userRoleNames" v-on:focus="selectRole" readonly></el-input>
                    </el-form-item>


                    <el-form-item label="建档时间：" prop="createTime">
                        <el-input v-model="ruleForm.createTime" readonly></el-input>
                    </el-form-item>

                    <el-form-item label="家庭住址：" prop="address">
                        <el-input v-model="ruleForm.address"></el-input>
                    </el-form-item>

                    <el-form-item label="证件信息：" prop="remark" class="member-mark">
                        <el-input type="textarea" v-model="ruleForm.remark"></el-input>
                    </el-form-item>

                    <el-form-item label="上传照片:" prop="upload" class="member-upload">
                        <div class="el-left">
                            <el-upload
                                    class="avatar-uploader"
                                    :action="uploadUrl"
                                    :show-file-list="false"
                                    :on-success="handleAvatarSuccess"
                                    :before-upload="beforeAvatarUpload"
                                    :on-error="onError">

                                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </div>
                    </el-form-item>
                </el-row>

            </el-form>


        </div>
    </div>
</template>


<script>
    import * as type from '../../../store/types';
    export default {
        data: function () {

            return {
                ruleForm: {},
                rulesUser: {},
                id: '',
                roles: [],
                organs: [],
                organ: [],
                result: [],
                loading: false,
                imageUrl: '',
                uploadUrl: this.$cfg.api_url + "/vue-uploads",
                status: false,
                currentSelected: [],
                isDisabled: false,
                beforeName:'',
                currentUser:{}
            }
        },
        watch: {
            ruleForm(val) {
                if (val.state) {
                    this.status = true;
                }
            },
            status(val){
                if (val) {
                    this.ruleForm.state = 1;
                } else {
                    this.ruleForm.state = 0;
                }
            }
        },

        activated: function () {
            this.$$("#content").scrollTop(0)
            let backInfo = this.$route.params;
            this.currentUser = JSON.parse(localStorage.getItem("currentUser"));
            this.currentSelected = [];
            console.log(backInfo)
            this.id = this.$route.query.id;
            if (this.id == undefined) {
                this.id = "";
            }
            this.result = [];
            //从选择列表进入info
            if (backInfo.flag != undefined) {
                console.log("============从选择列表进入info")
                if (backInfo.flag == 'selectOrgans') {
                    console.log("==========>selectOrgans");

                    this.$set(this.ruleForm, 'userOrganNames', backInfo.selected.name);
                    this.$set(this.ruleForm, 'userOrganIds', backInfo.selected.id);
                }
                else if (backInfo.flag == 'selectOrgan') {
                    console.log("==========>selectOrgan");
                    this.$set(this.ruleForm, 'primaryOrganName', backInfo.selected.name);
                    this.$set(this.ruleForm, 'primaryOrganId', backInfo.selected.id);
                    console.log(this.ruleForm)
                }
                else if (backInfo.flag == 'selectRoles') {
                    console.log("==========>selectRoles")
                    this.$set(this.ruleForm, 'userRoleNames', backInfo.selected.name);
                    this.$set(this.ruleForm, 'userRoleIds', backInfo.selected.id);
                } else if (backInfo.flag == 'back') {
                    console.log("==========>back");
                } else {
                    return;
                }


            }
            // 从自身列表页进入
            else {
                console.log("============从自身列表页进入")
                if (this.$route.query.new) {
                    console.log("============>新增");
                    this.ruleForm = {

                        account: '',
                        name: '',
                        tel: '',
                        email: '',
                        // state: '',
                        userOrganNames: '',
                        userOrganIds: '',
                        primaryOrganName: '',
                        primaryOrganId: '',
                        userRoleNames: '',
                        userRoleIds: '',
                        createTime: '',
                        address: '',
                        remark: '',
                        imageUrl: '',
                    };
                    this.currentSelected = [];
                    this.imageUrl = '';
                    this.isDisabled = false;
                } else if (this.id != "") {
                    this.isDisabled = true;
                    this.loading = true;
                    console.log("/user/" + this.id);
                    var that = this;
                    this.$axioxs.get("/user/" + this.id)
                        .then(function (res) {
                            console.log(JSON.stringify(res.data));
                            console.log(res.data);
                            that.loading = false;
                            that.ruleForm = res.data;
                            console.log("=============")
                            console.log(that.ruleForm.name)
                            that.beforeName=that.ruleForm.name;
                            if (that.ruleForm.portraitName) {
                                that.imageUrl = that.$cfg.static_url + "/" + that.ruleForm.portraitName;
                            }
                            else {
                                that.imageUrl = '';
                            }

                            if (that.ruleForm.state) {
                                that.status = true
                            } else {
                                that.status = false
                            }

                            console.log(that.ruleForm);


                        })
                        .catch(function (error) {
                            console.log(error);
                            that.$message({
                                showClose: true,
                                type: 'error',
                                message: error
                            });
                        });
                }
                else {
                    console.log("=========>chang tab");
                }
            }


        },
        methods: {
            back: function () {
                this.$store.commit(type.CHANGE_INDEX, '/user');
                this.$router.push({
                    path: '/user',
                });
            },
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        console.log(this.ruleForm);

                        let data = this.ruleForm;

                        console.log(data);
                        data.kindCode = 10;
                        console.log(11111111111)
                        console.log(this.$route)
                        if (this.$route.query.id == '') {
                            data.password = data.password || '123456';
                        } else {
                            data.password = data.password || "";
                        }
                        console.log(data)
                        this.loading = true;
                        let that = this;
                        this.$axioxs({
                            method: 'post',
                            url: '/user/',
                            data: data
                        })
                            .then(function (res) {
                                console.log(JSON.stringify(res.data));
                                that.loading = false;

                                var aaa = that.$store.state.username;
                                that.currentUser.name = aaa;

                                console.log("currentname",that.currentUser);
                                console.log("beforename",that.beforeName)
                                if(aaa == that.beforeName){
                                    that.$store.commit(type.CHANGE_NAME,  that.ruleForm.name);
                                    localStorage.setItem("currentUser", JSON.stringify(that.currentUser));
                                }else{

                                }
                                that.back();
                            })
                            .catch(function (error) {
                                console.log(error);
                                that.$message({
                                    showClose: true,
                                    type: 'error',
                                    message: error,
                                    onClose: function () {
                                        that.loading = false;
                                    }
                                });
                            });
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },

            selectOrgans: function () {
                console.log("====================>selectOrgans");
                console.log(this.id);
                console.log(this.$route.params);
                this.currentSelected = new Array();
                console.log(this.ruleForm.userOrganNames);
                if (this.ruleForm.userOrganNames) {
                    this.csv2IdNames(this.ruleForm.userOrganIds, this.ruleForm.userOrganNames);
                    console.log(this.result);
                    this.currentSelected = this.result;
                } else {
                    this.currentSelected = [];
                }


                if (this.currentSelected.length == 0) {
                    this.currentSelected = []
                }

                if (this.id == undefined) {
                    this.id = '';
                }

                this.$router.push({
                    name: 'select',
                    path: '/select/list',
                    query: {id: this.id},
                    params: {
                        toFlag: "selectOrgans",
                        currentSelected: this.currentSelected,
                        isMultiselect: true,
                        url: "/organ/?states=0,1",
                        backUrl: "/user/info?id=",
                        backUrlName: "u"
                    }

                });

            },
            selectOrgan: function () {
                console.log("====================>selectOrgan");
                console.log(this.id);
                console.log(this.$route.params);

                console.log(this.ruleForm);

                this.csv2IdNames(this.ruleForm.primaryOrganId, this.ruleForm.primaryOrganName);
                console.log(this.result);
                this.currentSelected = this.result;

                if (this.currentSelected.length == 0) {
                    this.currentSelected = []
                }

                if (this.id == undefined) {
                    this.id = '';
                }
                this.$router.push({
                    name: 'select',
                    path: '/select/list',
                    query: {id: this.id},
                    params: {
                        toFlag: "selectOrgan",
                        info: this.ruleForm,
                        currentSelected: this.currentSelected,
                        isMultiselect: false,
                        url: "/organ/?states=0,1",
                        backUrl: "/user/info?id=",
                        backUrlName: "u"
                    }

                });

            },
            selectRole: function () {
                console.log("========>selectRole");
                if (this.ruleForm.primaryOrganName) {  //选择仓库时已经有选择的了
                    this.csv2IdNames(this.ruleForm.userRoleIds, this.ruleForm.userRoleNames);
                    console.log(this.result);
                    this.currentSelected = this.result;
                } else {
                    this.currentSelected = [];
                }

                console.log(this.currentSelected)

                this.$router.push({
                    name: 'select',
                    path: '/select/list',
                    query: {id: this.id},
                    params: {
                        toFlag: "selectRoles",
                        info: this.ruleForm,
                        currentSelected: this.currentSelected,
                        isMultiselect: true,
                        url: "/role/",
                        backUrl: "/user/info?id=",
                        backUrlName: "u",
                        isHandler: false
                    }
                });

            },

            csv2IdNames: function (ids, names) {
                console.log(">>>>>>>>>>>>>>>>>>>csv2IdNames");
                console.log(ids);
                console.log(names);
                if (!ids || !names) {
                    return [];
                }

                if (typeof ids != "string" || typeof names != "string") {
                    return [];
                }
                var ids_arr = ids.replace(' ', '').split(',');
                var names_arr = names.replace(' ', '').split(',');

                console.log(ids_arr);
                console.log(names_arr);


                if (ids_arr.length !== names_arr.length) {
                    console.log("长度不一样");
                    return [];
                }


                let result = [];

                for (var i = 0; i < ids_arr.length; i++) {
                    var obj = {};
                    obj.id = (ids_arr[i]).trim();
                    obj.name = (names_arr[i]).trim();
                    result.push(obj);
                }


                console.log(result);
                this.result = [];
                this.result = result;


            },

            handleAvatarSuccess(res, file) {
                this.imageUrl = URL.createObjectURL(file.raw);
                if (res && res.length > 0) {
                    this.ruleForm.portraitId = res[0].id;//将图片实例ID保存在FORM中
                    this.ruleForm.portraitName = res[0].fileName
                }
                console.log(res)
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            onError: function (err, file, fileList) {
                alert(err)
            }


        }
    }

</script>
<style scoped>
    .avatar-uploader-icon {
        line-height: 178px;
    }

</style>
